import { login, logout, info } from '@/api/admin'
import { getToken, setToken, removeToken, getRSApassword } from '@/utils/auth'
import { cache } from '@/utils/index'
import { resetRouter, filterRouter } from '@/router'


const state = {
  token: getToken(),
  menus: [],
  name: '',
  avatar: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // admin login
  login({ commit }, { username, password }) {
    const sys_cfg = cache('sys_cfg')
    var pwd = password.trim()
    if (parseInt(sys_cfg.rsa_encrypt) === 1) {
      pwd = getRSApassword(sys_cfg.public_key, pwd)
    }
    // console.log('actions: admin/login ', username, pwd)
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: pwd
      }).then(response => {
        const { data } = response
        console.log('actions: admin/login data', data)
        commit('SET_TOKEN', data.token)

        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get admin info
  info({ commit, state }) {
    return new Promise((resolve, reject) => {
      info(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { menus, name, avatar } = data
        commit('SET_MENUS', filterRouter(menus))
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        // console.log('admin/info state.menus ', state.menus, state)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // admin logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        resolve()
        // 不需要清空 sys_cfg
        // cache('sys_cfg', null)
      }).catch(error => {
        console.log('admin logout error: ', error)
        // reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

